package cn.team11.smarteye.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import net.lucode.hackware.magicindicator.buildins.UIUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.team11.sds.dayi.R;
import cn.team11.smarteye.activity.CateyeDeviceDetailActivity;
import cn.team11.smarteye.activity.ScreenShotDetailActivity;
import cn.team11.smarteye.activity.callback.CaptureRecordCallback;
import cn.team11.smarteye.activity.callback.CaptureRecordResultCallback;
import cn.team11.smarteye.adapter.CaptureScreenGridAdapter;
import cn.team11.smarteye.base.BaseDialog;
import cn.team11.smarteye.base.BaseFragment;
import cn.team11.smarteye.base.BasePresenter;
import cn.team11.smarteye.bean.CaptureInfo;
import cn.team11.smarteye.misc.SConstants;
import cn.team11.smarteye.utils.AppLogger;
import cn.team11.smarteye.utils.ListUtils;
import cn.team11.smarteye.utils.TimeUtils;
import cn.team11.smarteye.widget.CaptureCalendarPopupView;
import cn.team11.smarteye.widget.CustomLoadingDialog;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.functions.Predicate;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by Murphy on 2017/11/1.
 */

public class CaptureRecordFragment extends BaseFragment implements CaptureRecordResultCallback, AdapterView.OnItemClickListener, CaptureCalendarPopupView.OnCalendarListener {
    @BindView(R.id.capture_record_gridview)
    GridView mCaptureGV;
    @BindView(R.id.no_capture_record_img)
    ImageView mNoCaptureView;
    @BindView(R.id.choose_time_bt_in_capture)
    TextView mChooseTime;
    @BindView(R.id.edit_mode_layout_capture)
    View mEditModeLayout;


    private CaptureRecordCallback mCallback;
    private List<CaptureInfo> mCapturesLists = new CopyOnWriteArrayList<>();
    private String seletedDate;
    private boolean isEditMode = false;
    private File rootDirs;


    private CaptureScreenGridAdapter mAdapter;

    public static CaptureRecordFragment newInstance(Bundle bundle) {
        CaptureRecordFragment fragment = new CaptureRecordFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_capture_record, container, false);
        ButterKnife.bind(this, view);
        init();
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        AppLogger.i("CaptureRecordFragment onCaptureViewCreated");
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }

    @Override
    public void setPresenter(BasePresenter presenter) {

    }


    @Override
    public void init() {
        ((CateyeDeviceDetailActivity)getActivity()).registerCaptureRecordResultCallback(this);
        mCallback = (CaptureRecordCallback) getActivity();
        seletedDate = TimeUtils.dateToString(new Date());
        mChooseTime.setText(seletedDate.substring(5, 10));

        String name = getArguments().getString(SConstants.NAME);
        rootDirs = new File(SConstants.SCREENSHOT_PATH + File.separator + name + File.separator);
        if (!rootDirs.exists()) rootDirs.mkdirs();
        mCapturesLists.clear();
        getAllCaptures(rootDirs);
        mAdapter = new CaptureScreenGridAdapter(mCapturesLists, getActivity());

        mCaptureGV.setAdapter(mAdapter);
        mCaptureGV.setOnItemClickListener(this);


    }

    private void getAllCaptures(File rootFile){
        Observable.fromArray(rootFile.listFiles())
                .filter(new Predicate<File>() {
                    @Override
                    public boolean test(@NonNull File file) throws Exception {
                        String fname = file.getName();
                        Long ftimestamp = Long.valueOf(fname.substring(0, fname.lastIndexOf(".")));
                        final long starttime = TimeUtils.stringToTimestamp(seletedDate + " 00:00:00");
                        return file.getName().endsWith(".png") ||
                                file.getName().endsWith(".jpg") &&
                                ftimestamp > starttime && ftimestamp < starttime + 86400000;
                    }
                })
                .map(new Function<File, String>() {
                    @Override
                    public String apply(@NonNull File file) throws Exception {
                        return file.getAbsolutePath();
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull String s) {
                        CaptureInfo info = new CaptureInfo(s, false);
                        mCapturesLists.add(info);
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {

                    }

                    @Override
                    public void onComplete() {
                        showCaptureTips();
                        mAdapter.notifyDataSetChanged();
                    }
                });

    }

    private void showCaptureTips(){
        if (ListUtils.isEmpty(mCapturesLists)){
            mNoCaptureView.setVisibility(View.VISIBLE);
        } else {
            mNoCaptureView.setVisibility(View.INVISIBLE);
        }
    }

    @OnClick({R.id.choose_time_bt_in_capture,R.id.capture_delete_bt})
    public void onClickAction(View view){
        switch (view.getId()){
            case R.id.choose_time_bt_in_capture:
                CaptureCalendarPopupView calendar = new CaptureCalendarPopupView(getActivity(), rootDirs);
                calendar.setOnCalendarListener(this);
                calendar.showAsDropDown(view, 0, 27);
                break;
            case R.id.capture_delete_bt:
                Bundle b = new Bundle();
                b.putString("title", getString(R.string.delete_capture_record));
                b.putString("content", getString(R.string.delete_capture_record_tips));
                final TextDialogFragment deleteDialog = TextDialogFragment.newInstance(b);
                deleteDialog.show(getFragmentManager(), "delete_guest_record");
                deleteDialog.setOnBtClickListener(new BaseDialog.OnBtClickListener() {

                    @Override
                    public void onConfirmClick() {
                        final CustomLoadingDialog loadingDialog = new CustomLoadingDialog(getActivity(), R.style.common_dialog_theme);
                        loadingDialog.show();
                        loadingDialog.setLoadingTips(getActivity().getResources().getString(R.string.is_deleting));
                        Observable.fromIterable(mCapturesLists)
                                .filter(new Predicate<CaptureInfo>() {
                                    @Override
                                    public boolean test(@NonNull CaptureInfo captureInfo) throws Exception {
                                        return captureInfo.isSelected();
                                    }
                                })
                                .map(new Function<CaptureInfo, Boolean>() {
                                    @Override
                                    public Boolean apply(@NonNull CaptureInfo captureInfo) throws Exception {
                                        mCapturesLists.remove(captureInfo);
                                        return new File(captureInfo.getPath()).delete();
                                    }
                                })
                                .subscribeOn(Schedulers.io())
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe(new Observer<Boolean>() {
                                    @Override
                                    public void onSubscribe(@NonNull Disposable d) {

                                    }

                                    @Override
                                    public void onNext(@NonNull Boolean ret) {
                                        //可以用来更新进度
                                        AppLogger.i("delete state: " + ret);
                                    }

                                    @Override
                                    public void onError(@NonNull Throwable e) {
                                        AppLogger.i("delete state: " + e.getMessage());
                                    }

                                    @Override
                                    public void onComplete() {
                                        showCaptureTips();
                                        leaveEditMode();
                                        loadingDialog.dismiss();
                                    }
                                });
                        deleteDialog.dismiss();
                    }

                    @Override
                    public void onCancelClick() {
                        deleteDialog.dismiss();
                    }
                });

                break;
        }
    }


    @Override
    public void onRightButtonClick(View view) {
        if (!isEditMode){
            enterEditMode();
        } else {
            leaveEditMode();
        }

    }


    @Override
    public void onLeftButtonOnClick(View view) {
        //全选操作
        if (isEditMode){
            for ( int i = 0; i < mCapturesLists.size(); i++){
                mCapturesLists.get(i).setSelected(true);
            }
            mAdapter.notifyDataSetChanged();
        } else {
            getActivity().finish();
        }
    }

     /**
     * 进入编辑状态
     * */
    private void enterEditMode(){
        if (mCallback != null){
            isEditMode = true;
            mCallback.setCanScroll(false);
            mEditModeLayout.setVisibility(View.VISIBLE);
            mCallback.setCustomTitle(getResources().getString(R.string.cancel), 1);
            mCallback.setCustomTitle(getResources().getString(R.string.select_all), -1);
            mCallback.setCustomTitleImage(null, -1);
            mCallback.setTabVisiable(View.GONE);
            mAdapter.setEditMode(isEditMode);
        }
    }

    /**
     * 离开编辑状态
     * */
    private void leaveEditMode(){
        if (mCallback != null){
            isEditMode = false;
            mCallback.setCanScroll(true);
            mEditModeLayout.setVisibility(View.INVISIBLE);
            mCallback.setCustomTitle(getResources().getString(R.string.edit_txt), 1);
            mCallback.setCustomTitle("", -1);
            Drawable iconDrawable = ContextCompat.getDrawable(getActivity(), R.drawable.nav_icon_back);
            iconDrawable.setBounds(0, 0, UIUtil.dip2px(getActivity(), 20), UIUtil.dip2px(getActivity(), 20));
            mCallback.setCustomTitleImage(iconDrawable, -1);
            mCallback.setTabVisiable(View.VISIBLE);
            mAdapter.setEditMode(isEditMode);
        }
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        if (isEditMode){
            CaptureScreenGridAdapter.ViewHolder holder = (CaptureScreenGridAdapter.ViewHolder) view.getTag();
            if (mCapturesLists.get(i).isSelected()){
                mCapturesLists.get(i).setSelected(false);
                holder.select_status.setSelected(false);
            }else {
                mCapturesLists.get(i).setSelected(true);
                holder.select_status.setSelected(true);
            }
        } else {
            ArrayList<String> imgPaths = new ArrayList<>();
            for (CaptureInfo info : mCapturesLists){
                imgPaths.add(info.getPath());
            }
            Intent intent = new Intent(getActivity(), ScreenShotDetailActivity.class);
            intent.putExtra(SConstants.IMAGE_INDEX, i);
            intent.putStringArrayListExtra(SConstants.IMAGE_PATH, imgPaths);
            getActivity().startActivity(intent);
        }
    }

    @Override
    public void onSelectedDateString(String dateStr) {
        mCapturesLists.clear();
        seletedDate = dateStr;
        mChooseTime.setText(dateStr.substring(5, 10));
        getAllCaptures(rootDirs);
    }

    @Override
    public void getAllSnapshots() {
        mCapturesLists.clear();
        getAllCaptures(rootDirs);
    }
}
